package com.shadow.core.net;


import com.shadow.core.app.ConfigType;
import com.shadow.core.app.Shadow;
import com.shadow.core.net.rx.RxRestService;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Created by zhangyu on 2017/10/19.
 */

public class RestCreator {

    public static RestService getResetService() {
        return RestServiceHolder.REST_SERVICE;
    }

    public static RxRestService getRxResetService() {
        return RxRestServiceHolder.RX_REST_SERVICE;
    }

    private static final class RetrofitHolder {
        private static final String BASE_URL = (String) Shadow.getConfiguration(ConfigType.API_HOST);
        private static final Retrofit RETROFIT_CLINT = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(HttpHolder.OK_HTTP_CLIENT)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }

    private static final class HttpHolder {
        private static final int TIME_OUT = 60;
        private static final OkHttpClient.Builder BUILDER = new OkHttpClient.Builder();
        private static final ArrayList<Interceptor> INTERCEPTORS = Shadow.getConfiguration(ConfigType.INTERCEPTOR);

        private static OkHttpClient.Builder addInterceptor() {
            if (INTERCEPTORS != null && !INTERCEPTORS.isEmpty()) {
                for (Interceptor interceptor : INTERCEPTORS) {
                    BUILDER.addInterceptor(interceptor);
                }
            }
            return BUILDER;
        }

        private static final OkHttpClient OK_HTTP_CLIENT = addInterceptor()
                .connectTimeout(TIME_OUT, TimeUnit.SECONDS)
                .readTimeout(TIME_OUT, TimeUnit.SECONDS)
                .writeTimeout(TIME_OUT,TimeUnit.SECONDS)
                .build();
    }

    private static final class RestServiceHolder {
        private static final RestService REST_SERVICE = RetrofitHolder.RETROFIT_CLINT
                .create(RestService.class);
    }

    private static final class RxRestServiceHolder {
        private static final RxRestService RX_REST_SERVICE = RetrofitHolder.RETROFIT_CLINT
                .create(RxRestService.class);
    }
}
